import CodeMirrorWrapper from '@/components/CodeMirrorWrapper';
import ToolPageTemplate from '@/components/ToolPageTemplate';
import { useBase64 } from '@/hooks/tools/useBase64';
import AutoFixHighIcon from '@mui/icons-material/AutoFixHigh';
import ContentCopyIcon from '@mui/icons-material/ContentCopy';
import DeleteIcon from '@mui/icons-material/Delete';
import FileUploadIcon from '@mui/icons-material/FileUpload';
import SecurityUpdateGoodIcon from '@mui/icons-material/SecurityUpdateGood';
import SwapHorizIcon from '@mui/icons-material/SwapHoriz';
import {
    Box, Button, ButtonGroup,
    FormControlLabel,
    Grid, Paper, Snackbar,
    Switch, Tooltip, Typography
} from '@mui/material';
import { useState } from 'react';

const Base64Page = () => {
    const [snackbarOpen, setSnackbarOpen] = useState(false);
    const [snackbarMessage, setSnackbarMessage] = useState('');
    const [urlSafe, setUrlSafe] = useState(false);
    const [autoDetect, setAutoDetect] = useState(true);

    const {
        inputContent,
        outputContent,
        setInputContent,
        encodeToBase64,
        decodeFromBase64,
        copyResult,
        clearAll,
        autoDetectAndProcess, // 新增自动检测处理函数
        loadExample
    } = useBase64({ urlSafe });

    const handleCopyResult = () => {
        copyResult();
        setSnackbarMessage('已复制到剪贴板');
        setSnackbarOpen(true);
    };

    const handleCloseSnackbar = () => {
        setSnackbarOpen(false);
    };

    const handleSwapContent = () => {
        if (outputContent) {
            setInputContent(outputContent);
            clearAll(true);
        }
    };

    const handleFileUpload = (event: { target: { files: any[]; }; }) => {
        const file = event.target.files[0];
        if (!file) return;

        const reader = new FileReader();

        if (file.size > 5 * 1024 * 1024) {
            setSnackbarMessage('文件过大，请上传小于5MB的文件');
            setSnackbarOpen(true);
            return;
        }

        reader.onload = (e) => {
            const content = e.target?.result;
            setInputContent(typeof content === 'string' ? content : '');
        };

        reader.onerror = () => {
            setSnackbarMessage('读取文件失败');
            setSnackbarOpen(true);
        };

        if (file.type.startsWith('text/') ||
            file.type === 'application/json' ||
            file.name.endsWith('.txt') ||
            file.name.endsWith('.json') ||
            file.name.endsWith('.xml') ||
            file.name.endsWith('.html')) {
            reader.readAsText(file);
        } else {
            reader.readAsDataURL(file);
        }
    };

    const handleAutoDetect = () => {
        if (autoDetect && inputContent.trim()) {
            autoDetectAndProcess();
        }
    };

    return (
        <ToolPageTemplate
            title="Base64 编码解码"
            description="Base64编码解码工具，支持文本和文件处理"
            category="格式转换"
            categoryColor="#FF9C6E"
        >

            {/* 选项区域 */}
            <Box sx={{ mb: 3, display: 'flex', justifyContent: 'center', flexWrap: 'wrap', gap: 2 }}>
                <FormControlLabel
                    control={
                        <Switch
                            checked={urlSafe}
                            onChange={(e) => setUrlSafe(e.target.checked)}
                        />
                    }
                    label="URL安全模式"
                />
                <FormControlLabel
                    control={
                        <Switch
                            checked={autoDetect}
                            onChange={(e) => setAutoDetect(e.target.checked)}
                        />
                    }
                    label="自动检测"
                />
                <Tooltip title="上传文件">
                    <Button
                        component="label"
                        variant="outlined"
                        startIcon={<FileUploadIcon />}
                    >
                        上传文件
                        <input
                            type="file"
                            hidden
                            onChange={(event: React.ChangeEvent<HTMLInputElement>) => {
                                if (event.target.files && event.target.files.length > 0) {
                                    handleFileUpload({ target: { files: Array.from(event.target.files) } });
                                }
                            }}
                        />
                    </Button>
                </Tooltip>
            </Box>

            {/* 工具内容区域 */}
            <Paper
                elevation={0}
                sx={{
                    p: 3,
                    borderRadius: 3,
                    border: '1px solid',
                    borderColor: 'divider',
                    width: '100%'
                }}
            >
                <Box sx={{
                    display: 'flex',
                    justifyContent: 'space-between',
                    alignItems: 'center',
                    mb: 3
                }}>
                    <Typography
                        variant="h6"
                        sx={{
                            fontWeight: 700,
                            display: 'flex',
                            alignItems: 'center',
                            gap: 1
                        }}
                    >
                        <SecurityUpdateGoodIcon color="primary" />
                        Base64 编辑器
                    </Typography>
                    <Button
                        variant="text"
                        size="small"
                        startIcon={<AutoFixHighIcon />}
                        onClick={loadExample}
                        sx={{
                            textTransform: 'none',
                            fontWeight: 600,
                            color: 'primary.main',
                            '&:hover': {
                                bgcolor: 'primary.main',
                                color: 'primary.contrastText'
                            }
                        }}
                    >
                        加载示例
                    </Button>
                </Box>

                <Grid container spacing={2}>
                    <Grid item xs={12} md={6}>
                        <Typography variant="subtitle2" gutterBottom sx={{ fontWeight: 600 }}>
                            输入内容:
                        </Typography>
                        <Box sx={{ borderRadius: 2, overflow: 'hidden', border: '1px solid', borderColor: 'divider' }}>
                            <CodeMirrorWrapper
                                label=""
                                value={inputContent}
                                onChange={(value) => {
                                    setInputContent(value);
                                    // 当内容变化且启用自动检测时，自动处理
                                    if (autoDetect && value.trim()) {
                                        // 使用setTimeout避免频繁处理
                                        setTimeout(() => autoDetectAndProcess(), 300);
                                    }
                                }}
                                height="300px"
                                language="text"
                                placeholder="在此输入要编码或解码的内容..."
                            />
                        </Box>
                    </Grid>

                    <Grid item xs={12} md={6}>
                        <Typography variant="subtitle2" gutterBottom sx={{ fontWeight: 600 }}>
                            输出结果:
                        </Typography>
                        <Box sx={{ borderRadius: 2, overflow: 'hidden', border: '1px solid', borderColor: 'divider' }}>
                            <CodeMirrorWrapper
                                label=""
                                value={outputContent}
                                onChange={() => { }}
                                height="300px"
                                language="text"
                                readOnly={true}
                            />
                        </Box>
                    </Grid>
                </Grid>

                <Box sx={{
                    display: 'flex',
                    flexDirection: { xs: 'column', sm: 'row' },
                    gap: 2,
                    mt: 3,
                    alignItems: { xs: 'stretch', sm: 'center' },
                    justifyContent: 'center'
                }}>
                    <ButtonGroup
                        variant="contained"
                        aria-label="Base64操作按钮组"
                        sx={{
                            flexWrap: { xs: 'wrap', md: 'nowrap' },
                            '& .MuiButton-root': {
                                flex: { xs: '1 0 auto', md: '0 1 auto' }
                            }
                        }}
                    >
                        <Tooltip title="将文本编码为Base64">
                            <Button
                                onClick={encodeToBase64}
                                disabled={!inputContent.trim()}
                            >
                                编码
                            </Button>
                        </Tooltip>
                        <Tooltip title="将Base64解码为文本">
                            <Button
                                onClick={decodeFromBase64}
                                disabled={!inputContent.trim()}
                            >
                                解码
                            </Button>
                        </Tooltip>
                        {autoDetect && (
                            <Tooltip title="自动检测并处理">
                                <Button
                                    onClick={handleAutoDetect}
                                    disabled={!inputContent.trim()}
                                    color="secondary"
                                >
                                    自动处理
                                </Button>
                            </Tooltip>
                        )}
                    </ButtonGroup>

                    <Tooltip title="交换输入和输出">
                        <Button
                            variant="outlined"
                            onClick={handleSwapContent}
                            startIcon={<SwapHorizIcon />}
                            disabled={!outputContent}
                        >
                            交换
                        </Button>
                    </Tooltip>

                    <Tooltip title="复制结果到剪贴板">
                        <Button
                            variant="outlined"
                            onClick={handleCopyResult}
                            startIcon={<ContentCopyIcon />}
                            disabled={!outputContent}
                        >
                            复制结果
                        </Button>
                    </Tooltip>

                    <Tooltip title="清空所有内容">
                        <Button
                            component="button"
                            variant="outlined"
                            color="error"
                            onClick={() => clearAll(false)}
                            startIcon={<DeleteIcon />}
                            disabled={!inputContent && !outputContent}
                        >
                            清空
                        </Button>
                    </Tooltip>
                </Box>
            </Paper>

            <Snackbar
                anchorOrigin={{ vertical: 'bottom', horizontal: 'right' }}
                open={snackbarOpen}
                autoHideDuration={3000}
                onClose={handleCloseSnackbar}
                message={snackbarMessage}
            />
        </ToolPageTemplate>
    );
};

export default Base64Page;